package cn.keepme.ep.user.controller;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.mail.MessagingException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.jeecgframework.core.common.controller.BaseController;
import org.jeecgframework.core.common.exception.BusinessException;
import org.jeecgframework.core.common.hibernate.qbc.CriteriaQuery;
import org.jeecgframework.core.common.model.json.AjaxJson;
import org.jeecgframework.core.common.model.json.DataGrid;
import org.jeecgframework.core.constant.Globals;
import org.jeecgframework.core.util.ExceptionUtil;
import org.jeecgframework.core.util.MyBeanUtils;
import org.jeecgframework.core.util.PropertiesUtil;
import org.jeecgframework.core.util.ResourceUtil;
import org.jeecgframework.core.util.StringUtil;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.entity.TemplateExportParams;
import org.jeecgframework.poi.excel.entity.vo.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.vo.TemplateExcelConstants;
import org.jeecgframework.tag.core.easyui.TagUtil;
import org.jeecgframework.web.sms.util.MailUtil;
import org.jeecgframework.web.system.service.SystemService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import cn.keepme.ep.constants.FGETQestionController;
import cn.keepme.ep.question.entity.FJobEntity;
import cn.keepme.ep.user.entity.FUserQuizEntity;
import cn.keepme.ep.user.service.FUserQuizServiceI;
import cn.keepme.ep.util.ParamsSign;



/**   
 * @Title: Controller
 * @Description: 考试人员信息
 * @author onlineGenerator
 * @date 2015-12-02 16:19:53
 * @version V1.0   
 *
 */
@Scope("prototype")
@Controller
@RequestMapping("/fUserQuizController")
public class FUserQuizController extends BaseController {
	/**
	 * Logger for this class
	 */
	private static final Logger logger = Logger.getLogger(FUserQuizController.class);

	@Autowired
	private FUserQuizServiceI fUserQuizService;
	@Autowired
	private SystemService systemService;
	private String message;
	
	public String getMessage() {
		return message;
	}

	public void setMessage(String message) {
		this.message = message;
	}


	/**
	 * 考试人员信息列表 页面跳转
	 * 
	 * @return
	 */
	@RequestMapping(params = "fUserQuiz")
	public ModelAndView fUserQuiz(HttpServletRequest request) {
//		System.out.println("####################################");
		return new ModelAndView("/manager/user/fUserQuizList");
	}

	/**
	 * easyui AJAX请求数据
	 * 
	 * @param request
	 * @param response
	 * @param dataGrid
	 * @param user
	 */

	@RequestMapping(params = "datagrid")
	public void datagrid(FUserQuizEntity fUserQuiz,HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) {
		CriteriaQuery cq = new CriteriaQuery(FUserQuizEntity.class, dataGrid);
		//查询条件组装器
		org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, fUserQuiz, request.getParameterMap());
		try{
		//自定义追加查询条件
		}catch (Exception e) {
			throw new BusinessException(e.getMessage());
		}
		cq.add();
		this.fUserQuizService.getDataGridReturn(cq, true);
		TagUtil.datagrid(response, dataGrid);
	}

	/**
	 * 删除考试人员信息
	 * 
	 * @return
	 */
	@RequestMapping(params = "doDel")
	@ResponseBody
	public AjaxJson doDel(FUserQuizEntity fUserQuiz, HttpServletRequest request) {
		AjaxJson j = new AjaxJson();
		fUserQuiz = systemService.getEntity(FUserQuizEntity.class, fUserQuiz.getId());
		message = "考试人员信息删除成功";
		try{
			fUserQuizService.delete(fUserQuiz);
			systemService.addLog(message, Globals.Log_Type_DEL, Globals.Log_Leavel_INFO);
		}catch(Exception e){
			e.printStackTrace();
			message = "考试人员信息删除失败";
			throw new BusinessException(e.getMessage());
		}
		j.setMsg(message);
		return j;
	}
	
	/**
	 * 删除考试人员信息
	 * 
	 * @return
	 */
	@RequestMapping(params = "doEmail1")
	@ResponseBody
	public AjaxJson doEmail1(FUserQuizEntity fUserQuiz, HttpServletRequest request) {
		AjaxJson j = new AjaxJson();
		PropertiesUtil util = new PropertiesUtil("sysConfig.properties");
		String url = util.readProperty("mail.url")+"?";
		fUserQuiz = systemService.getEntity(FUserQuizEntity.class, fUserQuiz.getId());
		
		message = "邮件发送成功";
		int user_id = fUserQuiz.getId();
		systemService.addLog(message, Globals.Log_Type_EXIT, Globals.Log_Leavel_INFO);
		
		url += ParamsSign.encode(fUserQuiz.getEmail(), user_id+"");
		url += "_"+user_id;
		int jobId = fUserQuiz.getJob();
		List<FJobEntity> fJob = systemService.findByQueryString("from FJobEntity where id="+jobId);
		try {
			MailUtil.sendEmail(util.readProperty("mail.smtpHost"), fUserQuiz.getEmail(), "聚力集团 - 研发中心 - 应试邀请函", util.readProperty("mail.context0")+fUserQuiz.getNickname()+util.readProperty("mail.context")+fJob.get(0).getName()
					+util.readProperty("mail.context1")+url+util.readProperty("mail.context2")+url+util.readProperty("mail.context3"), util.readProperty("mail.sender"), 
					util.readProperty("mail.user"), util.readProperty("mail.pwd"));
			
//			System.out.println("邮件发送成功");
			//邮件发送成功后更新链接有效时间
//			SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//			Date d = new Date();
//			systemService.updateBySqlString("update f_user_quiz set valid_date='"+format.format(new Date(d.getTime() + Integer.parseInt(util.readProperty("enable_date")) * 24 * 60 * 60 * 1000))
//							+"' where email='"+fUserQuiz.getEmail()+"'");
//			FGETQestionController.receiveRequestCard(fUserQuiz);
		} catch (MessagingException e1) {
			// TODO Auto-generated catch block
			message = "邮件发送失败";
			e1.printStackTrace();
		}
		
		j.setMsg(message);
		request.setAttribute("message", message);
		return j;
	}
	/**
	 * 批量删除考试人员信息
	 * 
	 * @return
	 */
	 @RequestMapping(params = "doBatchDel")
	@ResponseBody
	public AjaxJson doBatchDel(String ids,HttpServletRequest request){
		AjaxJson j = new AjaxJson();
		message = "考试人员信息删除成功";
		try{
			for(String id:ids.split(",")){
				FUserQuizEntity fUserQuiz = systemService.getEntity(FUserQuizEntity.class, 
				Integer.parseInt(id)
				);
				fUserQuizService.delete(fUserQuiz);
				systemService.addLog(message, Globals.Log_Type_DEL, Globals.Log_Leavel_INFO);
			}
		}catch(Exception e){
			e.printStackTrace();
			message = "考试人员信息删除失败";
			throw new BusinessException(e.getMessage());
		}
		j.setMsg(message);
		return j;
	}
	 
	/**
	 * 添加考试人员信息
	 * 
	 * @param ids
	 * @return
	 */
	@RequestMapping(params = "doAdd")
	@ResponseBody
	public AjaxJson doAdd(FUserQuizEntity fUserQuiz, HttpServletRequest request) {
		AjaxJson j = new AjaxJson();
		message = "考试人员信息添加成功";
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		PropertiesUtil util = new PropertiesUtil("sysConfig.properties");
		
		try{
			fUserQuiz.setCreateDatetime(new Date());
			fUserQuiz.setActiveDatetime(null);
			fUserQuiz.setIsActive(0);
			if(fUserQuiz.getType()==0){
				fUserQuiz.setValidDate(new Date(new Date().getTime()+Integer.parseInt(util.readProperty("enable_date")) * 24 * 60 * 60 * 1000));
			}
			fUserQuizService.save(fUserQuiz);
			systemService.addLog(message, Globals.Log_Type_INSERT, Globals.Log_Leavel_INFO);
		}catch(Exception e){
			e.printStackTrace();
			message = "考试人员信息添加失败";
			throw new BusinessException(e.getMessage());
		}
		j.setMsg(message);
		return j;
	}
	
	/**
	 * 更新考试人员信息
	 * 
	 * @param ids
	 * @return
	 */
	@RequestMapping(params = "doUpdate")
	@ResponseBody
	public AjaxJson doUpdate(FUserQuizEntity fUserQuiz, HttpServletRequest request) {
		AjaxJson j = new AjaxJson();
		message = "考试人员信息更新成功";
		FUserQuizEntity t = fUserQuizService.get(FUserQuizEntity.class, fUserQuiz.getId());
		try {
			MyBeanUtils.copyBeanNotNull2Bean(fUserQuiz, t);
			fUserQuizService.saveOrUpdate(t);
			systemService.addLog(message, Globals.Log_Type_UPDATE, Globals.Log_Leavel_INFO);
		} catch (Exception e) {
			e.printStackTrace();
			message = "考试人员信息更新失败";
			throw new BusinessException(e.getMessage());
		}
		j.setMsg(message);
		return j;
	}
	
	private String email_result  = "";
	/**
	 * 邮件发送结果
	 * 
	 * @param ids
	 * @return
	 */
	@RequestMapping(params = "doEmail")
	@ResponseBody
	public AjaxJson doEmail(FUserQuizEntity fUserQuiz, HttpServletRequest request) {
		AjaxJson j = new AjaxJson();
//		message = "考试人员信息添加成功";
		message = email_result;
		j.setMsg(message);
		return j;
	}
	
	/**
	 * 考试人员信息新增页面跳转
	 * 
	 * @return
	 */
	@RequestMapping(params = "goEmailResult")
	public ModelAndView goEmailResult(FUserQuizEntity fUserQuiz, HttpServletRequest req) {
		PropertiesUtil util = new PropertiesUtil("sysConfig.properties");
		String url = util.readProperty("mail.url")+"?";
		fUserQuiz = systemService.getEntity(FUserQuizEntity.class, fUserQuiz.getId());
		
		message = "邮件发送成功";
		int user_id = fUserQuiz.getId();
		systemService.addLog(message, Globals.Log_Type_EXIT, Globals.Log_Leavel_INFO);
		
		url += ParamsSign.encode(fUserQuiz.getEmail(), user_id+"");
		url += "_"+user_id;
		int jobId = fUserQuiz.getJob();
		List<FJobEntity> fJob = systemService.findByQueryString("from FJobEntity where id="+jobId);
		try {
			MailUtil.sendEmail(util.readProperty("mail.smtpHost"), fUserQuiz.getEmail(), "面试邀请邮件", fUserQuiz.getNickname()+util.readProperty("mail.context")+fJob.get(0).getName()
					+util.readProperty("mail.context1")+url+util.readProperty("mail.context2"), util.readProperty("mail.sender"), 
					util.readProperty("mail.user"), util.readProperty("mail.pwd"));
		} catch (MessagingException e1) {
			// TODO Auto-generated catch block
			message = "邮件发送失败";
			e1.printStackTrace();
		}
		email_result = message;
		req.setAttribute("email_message", message);
		return new ModelAndView("/manager/user/fUserQuiz-email");
	}
	
	
	/**
	 * 考试人员信息新增页面跳转
	 * 
	 * @return
	 */
	@RequestMapping(params = "goAdd")
	public ModelAndView goAdd(FUserQuizEntity fUserQuiz, HttpServletRequest req) {
		List<FJobEntity> list = fUserQuizService.findByQueryString("from FJobEntity");
		String[] str = new String[list.size()];
		for(int i=0;i<list.size();i++){
			str[i] = list.get(i).getName();
		}
		
		req.setAttribute("fJob", str);
		if (StringUtil.isNotEmpty(fUserQuiz.getId())) {
			fUserQuiz = fUserQuizService.getEntity(FUserQuizEntity.class, fUserQuiz.getId());
			
			req.setAttribute("fUserQuizPage", fUserQuiz);
		}
		
		return new ModelAndView("/manager/user/fUserQuiz-add");
	}
	
	/**
	 * 考试人员信息编辑页面跳转
	 * 
	 * @return
	 */
	@RequestMapping(params = "goUpdate")
	public ModelAndView goUpdate(FUserQuizEntity fUserQuiz, HttpServletRequest req) {
		if (StringUtil.isNotEmpty(fUserQuiz.getId())) {
			fUserQuiz = fUserQuizService.getEntity(FUserQuizEntity.class, fUserQuiz.getId());
			req.setAttribute("fUserQuizPage", fUserQuiz);
		}
		
		List<FJobEntity> list = fUserQuizService.findByQueryString("from FJobEntity");
		String[] str = new String[list.size()];
		for(int i=0;i<list.size();i++){
			str[i] = list.get(i).getName();
		}
		
		req.setAttribute("fJob", str);
		return new ModelAndView("/manager/user/fUserQuiz-update");
	}
	
	/**
	 * 导入功能跳转
	 * 
	 * @return
	 */
	@RequestMapping(params = "upload")
	public ModelAndView upload(HttpServletRequest req) {
		req.setAttribute("controller_name","fUserQuizController");
		return new ModelAndView("common/upload/pub_excel_upload");
	}
	
	/**
	 * 导出excel
	 * 
	 * @param request
	 * @param response
	 */
	@RequestMapping(params = "exportXls")
	public String exportXls(FUserQuizEntity fUserQuiz,HttpServletRequest request,HttpServletResponse response
			, DataGrid dataGrid,ModelMap modelMap) {
		CriteriaQuery cq = new CriteriaQuery(FUserQuizEntity.class, dataGrid);
		org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, fUserQuiz, request.getParameterMap());
		List<FUserQuizEntity> fUserQuizs = this.fUserQuizService.getListByCriteriaQuery(cq,false);
		modelMap.put(NormalExcelConstants.FILE_NAME,"考试人员信息");
		modelMap.put(NormalExcelConstants.CLASS,FUserQuizEntity.class);
		modelMap.put(NormalExcelConstants.PARAMS,new ExportParams("考试人员信息列表", "导出人:"+ResourceUtil.getSessionUserName().getRealName(),
			"导出信息"));
		modelMap.put(NormalExcelConstants.DATA_LIST,fUserQuizs);
		return NormalExcelConstants.JEECG_EXCEL_VIEW;
	}
	/**
	 * 导出excel 使模板
	 * 
	 * @param request
	 * @param response
	 */
	@RequestMapping(params = "exportXlsByT")
	public String exportXlsByT(FUserQuizEntity fUserQuiz,HttpServletRequest request,HttpServletResponse response
			, DataGrid dataGrid,ModelMap modelMap) {
		modelMap.put(TemplateExcelConstants.FILE_NAME, "考试人员信息");
		modelMap.put(TemplateExcelConstants.PARAMS,new TemplateExportParams("Excel模板地址"));
		modelMap.put(TemplateExcelConstants.MAP_DATA,null);
		modelMap.put(TemplateExcelConstants.CLASS,FUserQuizEntity.class);
		modelMap.put(TemplateExcelConstants.LIST_DATA,null);
		return TemplateExcelConstants.JEECG_TEMPLATE_EXCEL_VIEW;
	}
	
	@SuppressWarnings("unchecked")
	@RequestMapping(params = "importExcel", method = RequestMethod.POST)
	@ResponseBody
	public AjaxJson importExcel(HttpServletRequest request, HttpServletResponse response) {
		AjaxJson j = new AjaxJson();
		
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
		for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
			MultipartFile file = entity.getValue();// 获取上传文件对象
			ImportParams params = new ImportParams();
			params.setTitleRows(2);
			params.setHeadRows(1);
			params.setNeedSave(true);
			try {
				List<FUserQuizEntity> listFUserQuizEntitys = ExcelImportUtil.importExcel(file.getInputStream(),FUserQuizEntity.class,params);
				for (FUserQuizEntity fUserQuiz : listFUserQuizEntitys) {
					fUserQuizService.save(fUserQuiz);
				}
				j.setMsg("文件导入成功！");
			} catch (Exception e) {
				j.setMsg("文件导入失败！");
				logger.error(ExceptionUtil.getExceptionMessage(e));
			}finally{
				try {
					file.getInputStream().close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return j;
	}
	
}
